<template>
  <div class="goodslist">
    <!-- 搜索栏 -->
    <el-card class="searchcard">
        <el-form :inline="true" :model="searchForm" class="searchform">
            <el-form-item label="商品名称">
                <el-input v-model="searchForm.searchText" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item label="商品分类">
                <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
                    <el-option label="手机数码" value="1" />
                    <el-option label="家用电器" value="2" />
                    <el-option label="电脑办公" value="3" />
                    <el-option label="服装配饰" value="4" />
                </el-select>
            </el-form-item>
            <el-form-item label="价格区间">
                <el-input-number 
                v-model="searchForm.minPrice"
                :min="0"
                :precision="2"
                placeholder="最低价"
                style="width:130px" />
                <span class="mx2">-</span>
                <el-input-number 
                v-model="searchForm.maxPrice"
                :min="0"
                :precision="2"
                placeholder="最高价"
                style="width:130px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                </el-button>
                <el-button @click="resetSearch">
                    <el-icon><Refresh /></el-icon>
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <!-- 表格和工具栏 -->
    <el-card class="tablecard">
        <template #header>
            <div class="cardheader">
                <el-button type="primary" @click="handleAdd">
                    <el-icon><Plus /></el-icon>
                    新增商品
                </el-button>
            </div>
        </template>

        <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column prop="sales" label="销量" width="80" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              :src="'http://localhost:9191' + row.imgs"
              :preview-src-list="['http://localhost:9191' + row.imgs]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="primary" link @click="handleStatus(row)">
                <el-icon><SwitchButton /></el-icon>
                {{ row.status === 1 ? '下架' : '上架' }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { Search,Refresh,Plus,Edit,SwitchButton,Delete} from "@element-plus/icons-vue";
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const searchForm = reactive({
    searchText:'',
    categoryId:'',
    minPrice:null,
    maxPrice:null
})
// 获取商品列表
const getGoodsList = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/api/good/page',
      method: 'get',
      params: {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
        ...searchForm
      }
    })
    tableData.value = res.data.records
    total.value = res.data.total
    console.log(res);
    
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getGoodsList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增商品
const handleAdd = () => {
  router.push('/admin/index/sj')
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`/admin/index/sg:${row.id}`)
}

// 修改商品状态
const handleStatus = async (row) => {
  try {
    await request({
      url: `/good/status:${row.id}`,
      method: 'put',
      data: {
        status: row.status === 1 ? 0 : 1
      }
    })
    ElMessage.success('操作成功')
    getGoodsList()
  } catch (error) {
    console.error('修改商品状态失败:', error)
  }
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request({
        url: `/goods/${row.id}`,
        method: 'delete'
      })
      ElMessage.success('删除成功')
      getGoodsList()
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }).catch(() => {})
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getGoodsList()
}

onMounted(() => {
  getGoodsList()
})
</script>

<style scoped>
.searchcard{
    margin-bottom: 20px;
}
.searchform{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}
.cardheader{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.pagination{
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
.mx-2{
    margin: 0 8px;
}
</style>